<template>
  <div class="content-block block-half-2" v-loading="loading">
    <div class="info-head">{{ title }}</div>
    <div class="info-content">
      <v-chart
        :option="chartOption" style="width: 100%;height: 400px;"
        :theme="chartTheme" autoresize
      ></v-chart>
    </div>
  </div>
</template>

<script>
import MixinVchartTheme from '@/mixins/mixin-vchart-theme';
import { loadYearElectricityList, loadYearGasList, loadYearWaterList } from '@/api/energyDataManagement'
import { pieTooltipFormatter } from '@/utils'

export default {
  name: 'grid-item-three',
  mixins: [MixinVchartTheme],
  props: {
    title: String,
  },
  data () {
    return {
      loading: true,
      waterCount: '',
      electricCount: '',
      gasCount: '',
    }
  },
  computed: {
    energyVariety () {
      return this.$store.state.energyVariety
    },
    chartOption () {
      const data = this.energyVariety.map(v => ({
        name: v.name,
        value: this[v.value + 'Count']
      }))
      return {
        legend: {
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: pieTooltipFormatter,
        },
        series: [
          {
            name: this.title,
            type: 'pie',
            radius: [70, 130],
            center: ['50%', '50%'],
            itemStyle: {
              borderRadius: 8
            },
            data: data
          }
        ]
      }
    }
  },
  mounted () {
    this.queryData()
  },
  methods: {
    queryData () {
      this.loading = true
      const rq1 = loadYearElectricityList().then(res => {
        if (res.code === 200) {
          res.data = res.data || {}
          return res.data.val
        }
      })
      const rq2 = loadYearWaterList().then(res => {
        if (res.code === 200) {
          res.data = res.data || {}
          return res.data.val
        }
      })
      const rq3 = loadYearGasList().then(res => {
        if (res.code === 200) {
          res.data = res.data || {}
          return res.data.val
        }
      })
      return Promise.all([rq1, rq2, rq3]).then(([count1, count2, count3]) => {
        this.electricCount = count1
        this.waterCount = count2
        this.gasCount = count3
      }).finally(() => {
        this.loading = false
      })
    },
  },
}
</script>
